package tul.cot.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import tul.cot.job.InitStats;
import tul.cot.job.Migrations;


public class Pairs {
	private Map<String , Integer> pairs = new TreeMap<String, Integer>();
	private int pairsNum = 0;
	
	public void addPairs(File file) throws IOException {
		
		BufferedReader reader = new BufferedReader(new FileReader(file));
		String ps = null;
		while ((ps = reader.readLine()) != null) {
			String[] split = ps.split(Migrations.CSV_SEP);
			
			if (split.length != 2)
				throw new RuntimeException("Error during parsing pairs file");
			
			addPairs(split[0], split[1]);
		}
		reader.close();
	}

	private void addPairs(String from, String to) {
		
		String ps1 = String.format("%s%s%s", from, Migrations.PAIR_SEP, to);
		String ps2 = String.format("%s%s%s", to, Migrations.PAIR_SEP, from);
		
		++pairsNum;
		
		if (pairs.get(ps1) == null) {
			pairs.put(ps1, pairsNum);
		}
		
		if (pairs.get(ps2) == null) {
			pairs.put(ps2, pairsNum);
		}
	}
	
	public Map<String, Integer> getMap() {
		return pairs;
	}
	
	public String getPairsStr() {
		StringBuilder sb = new StringBuilder();
		for (String pair: pairs.keySet()) {
			
			if (sb.length() > 0) {
				sb.append(InitStats.PAIRS_SEP); 
			}
			
			sb.append(pair);
		}
		
		return sb.toString();
	}
}
